//
//  UpLoadMyPhoto.m
//  Comma
//
//  Created by 杜远洋 on 15-1-29.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "UpLoadMyPhoto.h"
#import "URLMacro.h"
@implementation UpLoadMyPhoto
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.myData = [NSMutableData data];
    }
    return self;
}

+ (void)uploadWithImageName:(NSString *)name imageData:(NSData *)imageData finish:(ConnectBlock)block
{
    UpLoadMyPhoto * p = [[UpLoadMyPhoto alloc] init];
    p.myBolck = block;
    [p startFormConnectWithImageName:name imageData:imageData];
}

- (void)startFormConnectWithImageName:(NSString *)name imageData:(NSData *)imageData
{
    NSURL * url = [NSURL URLWithString:URL_UPLOAD_AVATAR];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *formLine = @"--0xKhTmLbOuNdArY-44DF1AB4-7622-4163-948C-8A1FEADDBF27";
    NSMutableString *value = [NSMutableString stringWithFormat:@"%@\r\n", formLine];
    [value appendFormat:@"Content-Disposition: form-data; name=\"__avatar1\"; filename=\"%@\"\r\n", name];
    //声明上传文件的格式
    [value appendFormat:@"Content-Type: image/*\r\n\r\n"];
    NSMutableData *data = [NSMutableData dataWithData:[value dataUsingEncoding:NSUTF8StringEncoding]];
    [data appendData:imageData];
    [data appendData:[[NSString stringWithFormat:@"\r\n%@--", formLine] dataUsingEncoding:NSUTF8StringEncoding]];
    //    NSLog(@"value ====== %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [request setHTTPBody:data];
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",@"0xKhTmLbOuNdArY-44DF1AB4-7622-4163-948C-8A1FEADDBF27"];
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    [NSURLConnection connectionWithRequest:request delegate:self];
}



- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@",response);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_myData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //    NSLog(@"%@", [[NSString alloc] initWithData:_myData encoding:NSUTF8StringEncoding]);
    self.myBolck(_myData);
    NSLog(@"照片数据：%@",_myData);
}





@end
